package com.xsy.glsurfaceview

import android.content.Context
import android.opengl.GLES30
import android.opengl.GLSurfaceView
import android.opengl.Matrix.orthoM
import android.util.AttributeSet
import android.util.Log
import com.xsy.glsurfaceview.utils.ShaderUtils
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10


class MyGLSurfaceView3(context: Context, attributeSet: AttributeSet) :
    GLSurfaceView(context, attributeSet) {
        private var render: MyGLRender3
    init {
        setEGLContextClientVersion(3)
        val fragmentShaderCode = ShaderUtils.readFileFromAssets(context, TextureRender3.fragment_file_path)
        val vertexShaderCode = ShaderUtils.readFileFromAssets(context, TextureRender3.vertex_file_path)
        Log.d("MyGLSurfaceView", "fragment shader code: $fragmentShaderCode")
        Log.d("MyGLSurfaceView", "vertex shader code: $vertexShaderCode")
        render = MyGLRender3(context, vertexShaderCode, fragmentShaderCode)
        setRenderer(render)
        render
    }
    fun onDestroy() {
        render.onDestroy()
    }
}

class MyGLRender3(private val context: Context, private val vertexShaderCode: String, private val fragmentShaderCode: String) :
    GLSurfaceView.Renderer {
    private lateinit var textureRender: TextureRender3
    val projectionMatrix: FloatArray = FloatArray(16)
    override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
        GLES30.glClearColor(1.0f, 0.0f, 0.0f, 1.0f)
        textureRender = TextureRender3(context, vertexShaderCode, fragmentShaderCode)
    }

    override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
        GLES30.glViewport(0, 0, width, height)
        Log.d("MyGLSurfaceView", "width: $width")
        Log.d("MyGLSurfaceView", "height: $height")

        //计算正交投影矩阵，修正变形
        val aspectRatio =
            if (width > height) width.toFloat() / height.toFloat() else height.toFloat() / width.toFloat()
        if (width > height) {
            orthoM(projectionMatrix, 0, -aspectRatio, aspectRatio, -1f, 1f, -1f, 1f)
        } else {
            orthoM(projectionMatrix, 0, -1f, 1f, -aspectRatio, aspectRatio, -1f, 1f)
        }
        textureRender.setProjectMatrix(projectionMatrix)
    }

    override fun onDrawFrame(gl: GL10?) {
        GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
        textureRender.draw()
    }

    fun onDestroy(){
        textureRender.onDestroy()
    }

}